package cn.glow.readingcloud.account.task;


import cn.glow.readingcloud.account.dao.UserBookshelfMapper;
import cn.glow.readingcloud.account.pojo.UserBookshelf;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.Synchronized;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author Glow
 * @Date 2023-04-16 17:51:26
 * @Description 书架作业调度
 * @Version 1.0
 */
public class UserBookshelfTask  implements  Runnable{
    private static final Logger LOGGER = LoggerFactory.getLogger(UserBookshelfTask.class);
    /** 处理类型：1.新增 2.修改 3.删除 */
    private Integer syncType;
    private UserBookshelf bookshelf;
    private UserBookshelfMapper bookshelfMapper;
    private Integer userId;

    @Override
    public void run() {
        taskwork();
    }
    public synchronized void taskwork()
    {
        LOGGER.info("当前线程ID：{},开始运行书架作业调度",Thread.currentThread().getName());
        try{
            if(syncType == 1)
            {
                bookshelf.setUserId(userId);
                bookshelfMapper.insert(bookshelf);
            }
            else if(syncType == 2)
            {
                bookshelf.setUserId(userId);
                LambdaQueryWrapper<UserBookshelf> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(UserBookshelf::getUserId,userId);
                queryWrapper.eq(UserBookshelf::getBookId,bookshelf.getBookId());
                bookshelfMapper.update(bookshelf,queryWrapper);
            }
            else if(syncType == 3)
            {
                bookshelfMapper.deleteById(bookshelf);
            }
            Thread.sleep(1500);
        } catch (Exception ex){
            LOGGER.error("书架同步失败，同步类型[{}]，异常:{}", this.syncType, ex);
        }
        LOGGER.info("当前线程ID：{},已结束书架作业调度",Thread.currentThread().getName());

    }

    public UserBookshelfTask(){}
    public UserBookshelfTask(Integer syncType, UserBookshelf bookshelf, UserBookshelfMapper bookshelfMapper, Integer userId) {
        this.syncType = syncType;
        this.bookshelf = bookshelf;
        this.bookshelfMapper = bookshelfMapper;
        this.userId = userId;
    }
}
